import { ref, onMounted, onUnmounted } from 'vue'
import SpeakTTS from 'speak-tts'
import { useDictationStore } from './useDictation'

interface TTSOptions {
  volume?: number
  rate?: number
  voice?: string
  lang?: string
}

export const useTTS = () => {
  const speakTTS = ref<SpeakTTS | null>(null)
  const isSpeakTTSAvailable = ref(false)
  const isSpeaking = ref(false)
  
  const dictationStore = useDictationStore()

  // 初始化SpeakTTS
  const initializeSpeakTTS = async () => {
    if (!speakTTS.value) {
      speakTTS.value = new SpeakTTS()
      try {
        // 确保配置已存在
        const volume = dictationStore.config?.value?.volume ?? 1.0
        const rate = dictationStore.config?.value?.rate ?? 1.0
        
        await speakTTS.value.init({
          volume: volume,
          rate: rate,
          pitch: 1,
          voice: undefined, // 后面会根据配置选择
          lang: 'en-GB', // 英语
        })
        isSpeakTTSAvailable.value = true
        console.log('SpeakTTS初始化成功')
      } catch (e) {
        console.error('SpeakTTS初始化失败:', e)
        isSpeakTTSAvailable.value = false
      }
    }
  }

  // 使用Tauri后端TTS
  const speakWithTauri = async (word: string) => {
    try {
      await window.__TAURI__.invoke('speak_word', { word })
      isSpeaking.value = true
      return true
    } catch (error) {
      console.warn('Tauri TTS失败:', error)
      return false
    }
  }

  // 使用speak-tts库播放单词
  const speakWithSpeakTTS = async (word: string) => {
    if (!isSpeakTTSAvailable.value || !speakTTS.value) {
      console.error('speak-tts不可用')
      return false
    }

    try {
      // 取消之前的播放
      speakTTS.value.speak.cancel()

      // 设置配置参数（安全访问）
      const volume = dictationStore.config?.value?.volume ?? 1.0
      const rate = dictationStore.config?.value?.rate ?? 1.0
      const voice = dictationStore.config?.value?.voice ?? undefined
      
      await speakTTS.value.setVolume(volume)
      await speakTTS.value.setRate(rate)

      // 获取可用语音并尝试设置
      const voices = speakTTS.value.getVoices()
      if (voice && voices.includes(voice)) {
        await speakTTS.value.setVoice(voice)
      }

      // 播放单词
      await speakTTS.value.speak({
        text: word,
        queue: false,
        onError: (error) => {
          console.error('SpeakTTS播放失败:', error)
          isSpeaking.value = false
        },
        onEnd: () => {
          isSpeaking.value = false
        }
      })
      
      isSpeaking.value = true
      return true
    } catch (error) {
      console.error('使用speak-tts播放失败:', error)
      isSpeaking.value = false
      return false
    }
  }

  // 使用浏览器Web Speech API朗读单词
  const speakWithWebAPI = (word: string) => {
    if ('speechSynthesis' in window) {
      // 取消之前的语音
      window.speechSynthesis.cancel()

      const utterance = new SpeechSynthesisUtterance(word)
      utterance.lang = 'en-US' // 设置为英语

      // 可以根据配置调整参数（安全访问）
      const rate = dictationStore.config?.value?.rate ?? 1.0
      const volume = dictationStore.config?.value?.volume ?? 1.0
      utterance.rate = rate
      utterance.volume = volume

      // 获取可用的语音（安全访问）
      const voice = dictationStore.config?.value?.voice ?? undefined
      if (voice) {
        const voices = speechSynthesis.getVoices()
        const selectedVoice = voices.find(voice => voice.name === dictationStore.config?.value?.voice)
        if (selectedVoice) {
          utterance.voice = selectedVoice
        }
      }
      
      utterance.onend = () => {
        isSpeaking.value = false
      }
      
      utterance.onerror = (event) => {
        console.error('Web Speech API朗读失败:', event)
        isSpeaking.value = false
      }

      window.speechSynthesis.speak(utterance)
      isSpeaking.value = true
      return true
    } else {
      console.error('浏览器不支持Web Speech API')
      return false
    }
  }

  // 通用的朗读函数，按优先级依次尝试
  const speak = async (word: string) => {
    if (!word || word === '-') {
      console.warn('单词为空，无法朗读')
      return
    }

    console.log('开始尝试播放单词:', word);
    
    // 优先尝试Tauri后端TTS
    if (await speakWithTauri(word)) {
      console.log('使用Tauri后端TTS播放成功');
      return
    } else {
      console.log('Tauri后端TTS失败，尝试其他方式');
    }

    // 然后尝试SpeakTTS
    if (await speakWithSpeakTTS(word)) {
      console.log('使用SpeakTTS播放成功');
      return
    } else {
      console.log('SpeakTTS失败，尝试浏览器Web Speech API');
    }

    // 最后使用浏览器Web Speech API
    const webApiSuccess = speakWithWebAPI(word);
    if (webApiSuccess) {
      console.log('使用浏览器Web Speech API播放成功');
    } else {
      console.warn('所有TTS方式都失败了');
    }
  }

  // 停止朗读
  const stopSpeaking = async () => {
    try {
      // 尝试停止Tauri后端播放
      await window.__TAURI__.invoke('set_playing', { playing: false })
    } catch (error) {
      console.warn('无法调用后端停止播放:', error)
    }

    // 如果SpeakTTS可用，也停止播放
    if (isSpeakTTSAvailable.value && speakTTS.value) {
      speakTTS.value.speak.cancel()
    }

    // 停止浏览器Web Speech API播放
    if ('speechSynthesis' in window) {
      window.speechSynthesis.cancel()
    }

    isSpeaking.value = false
  }

  onMounted(() => {
    initializeSpeakTTS()
  })

  // 在组件卸载时清理
  onUnmounted(() => {
    if (speakTTS.value) {
      speakTTS.value.speak.cancel()
    }
  })

  return {
    speak,
    stopSpeaking,
    isSpeaking,
    isSpeakTTSAvailable
  }
}